/*
 * @Description: 更新日志管理上下文
 * @Author: Rfan
 * @Date: 2022-06-11 09:59:07
 * @LastEditTime: 2022-06-11 15:14:27
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message, Modal } from 'antd';
import {
  ADD_CHANGELOG,
  DELETE_CHANGELOG,
  EDIT_CHANGELOG,
  HIDE_LOADING,
  LOADING,
  SET_CHANGELOG_LIST
} from '../constants';
import { ChangeLogReducer } from '../reducers/ChangeLogReducer';
import { deleteChangeLog, fetchChangeLogList, saveChangeLog } from '@/api/system';

const initialState = {
  loading: false,
  list: []
};

const ChangeLogContext = createContext();

const ChangeLogContextProvider = (props) => {
  const [state, dispatch] = useReducer(ChangeLogReducer, initialState);

  const actions = {
    /**
     * @description: 增加更新日志
     * @param {*} params 增加更新日志的参数
     * @return {*} 增加的更新日志
     */
    onAddChangeLog(params) {
      return new Promise((resolve, reject) => {
        saveChangeLog(params)
          .then((res) => {
            const { data } = res;
            message.success('添加成功');
            dispatch({ type: ADD_CHANGELOG, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 删除更新日志
     * @param {*} data 删除更新日志的ID
     */
    onDeleteChangeLog(id) {
      Modal.confirm({
        title: '删除',
        content: '确认删除选中的更新日志？',
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteChangeLog(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_CHANGELOG, ids: data });
          });
        },
        onCancel() {
          console.log('del unit Cancel');
        }
      });
    },

    /**
     * @description: 编辑更新日志
     * @param {*} params 编辑更新日志的参数
     */
    onEditChangeLog(params) {
      return new Promise((resolve, reject) => {
        saveChangeLog(params)
          .then((res) => {
            message.success('编辑成功');
            const { data } = res;
            const { id } = data;
            dispatch({ type: EDIT_CHANGELOG, id, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 按页获取更新日志列表
     */
    async fetchData() {
      dispatch({ type: LOADING });
      console.log('fetch');
      fetchChangeLogList({})
        .then((res) => {
          const { data } = res;
          dispatch({ type: SET_CHANGELOG_LIST, data });
        })
        .finally(() => {
          dispatch({ type: HIDE_LOADING });
        });
    }
  };

  const filters = {
    /**
     * @description: 更新日志状态过滤器
     * @param {number} code 状态Key
     * @return {string} 状态名
     */
    stateFilter(code) {
      return state.stateList.find((item) => item.id === code)?.name || '-';
    }
  };

  useEffect(() => {
    actions.fetchData();
  }, []);

  return (
    <ChangeLogContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </ChangeLogContext.Provider>
  );
};

export const useChangeLogContext = () => {
  return useContext(ChangeLogContext);
};

export { ChangeLogContext, ChangeLogContextProvider };
